import React from 'react';
import { Radio, Toast, Icon, Picker, Button, InputItem, List, DatePicker, Flex, Modal, Checkbox } from 'antd-mobile';
import { createForm } from 'rc-form';
import _ from 'lodash';
import moment from 'moment';
import styles from './VipRegForm.less';
import { fetchVerifyCode, fetchPaidVip , fetchSaleMan, fetchTags} from '../../services/vipService';
import PaidVip from '../../components/Base/PaidVip';
const Item = List.Item;
let defaultDistance=99999999999999999999999999999999999999999999999;
const alert = Modal.alert;
const CheckboxItem = Checkbox.CheckboxItem

class VipRegForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      saleMan: [],
      branchNo: [],
      timer: null,
      timeLimit: 0,
      loading: false,
      paidVip: null,
      isVisible: false,
      isVisible2: false,
      skinRadio: '',
      skinCheckbox: [],
      skin: [
        {value: '中性', label: '中性', isChecked: false},
        {value: '干性', label: '干性', isChecked: false},
        {value: '油性', label: '油性', isChecked: false},
        {value: '混油', label: '混油', isChecked: false},
        {value: '混干', label: '混干', isChecked: false},
        {value: '敏感', label: '敏感', isChecked: false},
      ],
      skinChange: [
        {value: '大油田', label: '大油田', isChecked: false},
        {value: '干燥起皮', label: '干燥起皮', isChecked: false},
        {value: '毛孔粗大', label: '毛孔粗大', isChecked: false},
        {value: '色斑', label: '色斑', isChecked: false},
        {value: '暗黄', label: '暗黄', isChecked: false},
        {value: '黑头白头', label: '黑头白头', isChecked: false},
        {value: '痘痘痘印', label: '痘痘痘印', isChecked: false},
        {value: '闭口', label: '闭口', isChecked: false},
        {value: '衰老皱纹', label: '衰老皱纹', isChecked: false},
        {value: '皮肤敏感', label: '皮肤敏感', isChecked: false},
        {value: '红血丝', label: '红血丝', isChecked: false},
        {value: '黑眼圈', label: '黑眼圈', isChecked: false},
        {value: '眼袋', label: '眼袋', isChecked: false}
      ]
    };
  }

  componentDidMount() {
    const shopId = this.props.location.query.shopId;
    fetchPaidVip(shopId).then((res) => {
      if (res.data && res.data.length) {
        this.setState({
          paidVip: res.data[0],
        });
      }
    });

  /* 获取皮肤标签 */
  this.getTags(shopId)
  }

    /* 获取皮肤标签 */
    getTags = (shopId) => {
      fetchTags(shopId).then( res => {
        console.log('获取皮肤标签', res)
        let {data} = res
        
        let index = data.findIndex( v => v.group_name === '肤质') 
        let indexP = data.findIndex( v => v.group_name === '皮肤问题')
  
        let skin = []
        let skinChange = []
  
        if (index != -1) {
          skin = data[index].tags.map( v => v = {"value": v, "label": v, "isChecked": false})
        }
  
        if (indexP != -1) {
          skinChange = data[indexP].tags.map( v => v = {"value": v, "label": v, "isChecked": false})
        }
        this.setState({
          skin,
          skinChange
        })
        console.log('skin,skinchange', this.state.skin, this.state.skinChange)
      })
    }
  /* 获取导购 */
  getSaleMan = async (shopId, branchId) => {
    let res = await fetchSaleMan(shopId, branchId)
    if (res.data.length){
      let saleMan = res.data.map(v => ({value: v.sale_id, label: v.sale_name}))
      this.setState({
        saleMan
      })
    } 
  }
  
  branchChange = (v) => {
    const shopId = this.props.location.query.shopId;
    v = v[0].split('-')[0]
    this.getSaleMan(shopId, v)
  }


  componentWillUnmount() {
    clearInterval(this.state.timer);
  }

  beginTimeLimit = () => {
    let seconds = 60;
    this.setState({
      timeLimit: seconds,
    });
    const timer = setInterval(() => {
      --seconds;
      this.setState({
        timeLimit: seconds,
      });
      if (seconds < 0) {
        clearInterval(timer);
        this.setState({
          timeLimit: 0,
          timer: 0,
        });
      }
    }, 1000);
    this.setState({
      timer,
    });
  };

  endTimeLimit = () => {
    setTimeout(() => {
      clearInterval(this.state.timer);
      this.setState({
        timeLimit: 0,
      });
    }, 1);
  }

  sendVerifyCode = () => {
    this.beginTimeLimit();
    if (this.state.timeLimit && +this.state.timeLimit > 0) {
      return;
    }

    const shopId = this.props.location.query.shopId;
    this.props.form.validateFields(['mobile'], (error, value) => {
      if (value.mobile) {
        const phone = value.mobile.replace(/\s/ig, '');
        fetchVerifyCode(phone, shopId, { type: 4, reg: true }).then(() => {
          Toast.success('验证码发送成功');
        }).catch((e) => {
          Toast.fail('获取验证码失败');
          this.endTimeLimit();
        });
      } else {
        Toast.info('请输入手机号');
        this.endTimeLimit();
      }
    });
  };

  getBranchData = () => {
    return _.map(this.props.branchList, (v) => {
      let label = v.branch_name;
      if (v.distance&&v.distance!==defaultDistance) {
        let distance=v.distance>1000?`${(v.distance/1000).toFixed(2)}km`:`${v.distance.toFixed(2)}m`
        label += ` - 距离${distance}`;
      }
      return { label, value: `${v.branch_no}-${v.branch_name}` };
    });
  };

  /* 收集表单 */
  submit = () => {
    let {skinRadio, skinCheckbox, saleMan} = this.state
    this.props.form.validateFields((error) => {
      if (!error) {
        if (this.props.onSubmit) {
          const value = this.props.form.getFieldsValue();
          // 肤质，肤质问题
          value.skinType = skinRadio || ''
          value.skinProblem = skinCheckbox.length ? skinCheckbox.join(',') : ''
          
          if (value.mobile) {
            value.mobile = value.mobile.replace(/\s/ig, '');
          }
          if (value.branch) {
            const val = value.branch[0];
            let index;
            const shopId = this.props.location.query.shopId;
            if(shopId.indexOf("yky")>=0) {
              index =val.lastIndexOf('-');
            }else{
              index =val.indexOf('-');
            }
            value.branchId = val.substring(0, index);
            value.branch_name = val.substring(index + 1);
            delete value.branch;
          }
          if(value.saleman_id) {
            value.saleman_id = value.saleman_id[0]
            value.saleman_name = saleMan.some( v => v.value == value.saleman_id[0])
          }
          if (value.vip_sex) {
            value.vip_sex = value.vip_sex[0];
          }
          if (value.birthday) {
            value.birthday = value.birthday.startOf('day');
          }

          if (!_.isNil(value.paid_card_type)) {
            value.isPaidVip = true;
            value.cardType = value.paid_card_type[0] || value.paid_card_type;
            delete value.paid_card_type;
          }

          console.log('表单数据', value)
          this.props.onSubmit(value);
          this.setState({
            loading: true,
          });
        }
      } else {
        Toast.fail(_.map(error, (v) => {
          return _.get(v, 'errors[0].message');
        })[0], 2);
        this.setState({
          loading: false,
        });
      }
    });
  };

  renderBranchSelect = (branchNo) => {
    const config = {
      rules: [{ required: true, message: '请选择门店' }],
    };
    if (branchNo) {
      const branchList = this.props.branchList;
      let branchName = '';
      _.forEach(branchList, (branch) => {
        if (branch.branch_no == branchNo) {
          branchName = branch.branch_name;
          return false;
        }
      });
      if (branchNo && branchName) {
        config.initialValue = [`${branchNo}-${branchName}`];
      }
    }

    return (<Picker
      onOk={ (v) => this.branchChange(v)}
      title="选择门店"
      data={this.getBranchData()}
      cols={1}
      {...this.props.form.getFieldProps('branch', config)}
    >
      <List.Item arrow="horizontal">选择门店</List.Item>
    </Picker>);
  };

  renderHeader = () => {
    return (<div style={{ position: 'relative' }}>
      会员注册
      { this.props.closable &&
      <span
        style={{
          position: 'absolute', right: 3, top: -5,
        }}
        onClick={() => {
          if (this.props.onClose) {
            this.props.onClose();
          }
        }}
      >
        <Icon type="cross" />
      </span>
      }
    </div>);
  };

/* 肤质 */
radio = (val) => {
  let {skin} = this.state
  let index = skin.findIndex(v => v.value == val)
  skin.forEach(v => v.isChecked = false)
  skin[index].isChecked = true
  this.setState({
    skin,
    skinRadio: skin[index].value
  })

}

/* 三个肤质问题 */
checkbox = (val) => {
  let {skinCheckbox, skinChange} = this.state
  // 表单数组
  let formIndex = skinCheckbox.findIndex( v => v===val)
  // 渲染数组
  let index = skinChange.findIndex(v => v.value===val)

  if (formIndex !== -1 && skinCheckbox.length <= 3) {
    skinChange[index].isChecked = false
    skinCheckbox.splice(formIndex, 1)
  }else if (formIndex === -1 && skinCheckbox.length === 3){
    Toast.info('只能选择三个肤质问题哟', 1.5)
  } else if (formIndex === -1 && skinCheckbox.length < 3) {
    skinCheckbox.push(val)
    skinChange[index].isChecked = true
  }

  this.setState({
    skinChange,
    skinCheckbox
  })

  console.log(this.state.skinCheckbox)
}


  styleShowSkin = {
    width: '100%',
    height: '1rem',
    lineHeight: '1rem',
    fontWeight: 'bold',
    color: '#333333',
    fontSize: '.386473rem',
    background: '#F2F2F2',
    position: 'absolute',
    left: '0',
    top: '0'
  }
  styleShowSkinBoby = {
    marginTop: '.5rem',
    display: 'flex',
    textAlign: 'center',
    alignItems: 'center',
    flexFlow: 'wrap',
    fontSize: '.326087rem',
  }

  /* skin复选框 */
  showSkinBody = (isChecked) => {
    let data = []
    const {skin, skinChange} = this.state
    if (!isChecked || isChecked === 0) {
      data = skin
      return (
        <div style={this.styleShowSkinBoby}>
          {data.map(i => (
             <div style={{margin: '0 auto', width: '33.33%', boxSizing: 'border-box', paddingLeft: '0.3rem'}} className={styles.pdiv} key={i.value}>
              <CheckboxItem
                checked={i.isChecked}
                onChange={() => this.radio(i.value)}>
                <span style={{color: '#666', fontWeight: 'normal'}}>{i.value}</span>
              </CheckboxItem>
            </div>
          ))}
        </div>
      )
    }else {
      data = skinChange
      return (
        <div style={this.styleShowSkinBoby}>
           {data.map(i => (
             <div style={{width: '33.33%'}} className={styles.checkbox2}>
              <CheckboxItem 
                checked={i.isChecked}
                key={i.value} 
                onChange={() => this.checkbox(i.value)}>
                <span style={{color: '#666', fontWeight: 'normal'}}>{i.label}</span>
              </CheckboxItem>
            </div>
          ))}
        </div>
      )
    }
  }

  render() {
    (<Modal></Modal>).props.style.width = '85%'
    const { getFieldProps, getFieldError } = this.props.form;
    let codeBtnClass = '';
    if (this.state.timeLimit > 0) {
      codeBtnClass = 'disableCodeBtn';
    }

    const shopId = this.props.location.query.shopId;
    const { paidVip } = this.state;
    let isPaidVip = false;
    if (paidVip && paidVip.enable && paidVip.paidCardTypes && paidVip.paidCardTypes.length) {
      isPaidVip = true;
    }
    /* 门店列表 */
    const branchNo = this.props.branchNo;
    const salemanId = this.props.salemanId;
    return (
    <div className={styles.indexWrap}>
      {/* 肤质单选 */}
    <Modal 
    visible={this.state.isVisible}
    transparent
    maskClosable
    title={<div style={this.styleShowSkin}>选择肤质</div>}
    footer={[
      {text: '取消', onPress: () => {this.setState({isVisible: false})}},
      {
        text: '确定', 
        onPress: () => {this.setState({isVisible: false})},
        style: {color: '#3ED2DF'}
      }
    ]}
  >
    {this.showSkinBody(0)}
  </Modal>
  {/* 肤质三个选项 */}
  <Modal 
    visible={this.state.isVisible2}
    transparent
    maskClosable
    title={<div style={this.styleShowSkin}>急需改善的三个皮肤问题</div>}
    footer={[
      {text: '取消', onPress: () => {this.setState({isVisible2: false})}},
      { 
        text: '确定', 
        onPress: () => {this.setState({isVisible2: false})},
        style: {color: '#3ED2DF'}
      }
    ]}
  >
    {this.showSkinBody(1)}
  </Modal>
      <div className="vipRegForm">
     {/*  <Header header={{message: 'testheader'}}></Header> */}
      <List
        className={styles.popupList}
      >
          <InputItem
          error={!!getFieldError('vip_name')}
          {...getFieldProps('vip_name', {
            rules: [{ required: true, message: '请输入您的名字' }],
          })}
          type="text"
          placeholder="请输入您的名字"
          className={styles.placeholderRight}
          style={{height: '1.5rem'}}
        >姓名</InputItem>

        {/* 性别 */}
        <Picker
          data={[
            {
              label: '男',
              value: '男',
            },
            {
              label: '女',
              value: '女',
            }]}
          cols={1}
          {...getFieldProps('vip_sex', {
            rules: [{ required: true, message: '请选择性别' }],
          })}
        >
          <List.Item arrow="horizontal">性别</List.Item>
        </Picker>

        {/* 手机号码 */}
        <InputItem
          error={!!getFieldError('mobile')}
          {...getFieldProps('mobile', {
            rules: [{ required: true, message: '请输入您的手机号码' }],
          }) }
          type="phone"
          placeholder="请输入您的手机号码"
          style={{height: '1.2rem'}}
        >手机</InputItem>

      <div className="codeRow">
          <Flex>
            <Flex.Item style={{ flex: 5 }}>
              <InputItem
                error={!!getFieldError('verifyCode')}
                {...getFieldProps('verifyCode', {
                  rules: [{ required: true, message: '请输入验证码' }],
                }) }
                type="number"
                style={{height: '1.2rem'}}
              >验证码
              </InputItem>
            </Flex.Item>
            <Flex.Item style={{ flex: 3 }}>
              <div className="codeButton" style={{overflow: 'none'}}>
                <Button disabled={this.state.timeLimit > 0} className={codeBtnClass} style={{fontSize: '.386473rem', marginLeft: '0', height: '.797101rem',width: '2.342995rem', borderRadius: '.144928rem', lineHeight: '.797101rem'}} onClick={this.sendVerifyCode} type="primary" size="large">
                  {this.state.timeLimit > 0 ? '请等待' + this.state.timeLimit + '秒' : '获取验证码'}
                </Button>
              </div>
            </Flex.Item>
          </Flex>
        </div>

        <DatePicker
          mode="date"
          title="选择生日"
          maxDate={moment().add(2, 'years')}
          minDate={moment().subtract(12, 'years')}
          {...getFieldProps('birthday', {
            rules: [{ required: true, message: '请选择您的生日' }],
          })}
        >
          <List.Item arrow="horizontal">生日<span style={{color: 'red'}}>*</span></List.Item>
        </DatePicker>
        
        {/* 肤质要弹框选择   List.Item arrow="horizontal">肤质</List.Item>*/}
        <div onClick={() => this.setState({isVisible: true})}>
        <Picker disabled extra={this.state.skinRadio ? this.state.skinRadio : '请选择'}>
          <List.Item arrow="horizontal">肤质</List.Item>
        </Picker>
        </div>
        {/* 需要改善的皮肤问题 弹框选择*/}
        <div onClick={() => {this.setState({isVisible2: true})}} >
        <Picker disabled extra={this.state.skinCheckbox.length !==0 ? this.state.skinCheckbox.join(' ') : '请选择'}>
          <List.Item arrow="horizontal">需要改善的皮肤问题</List.Item>
        </Picker>
        </div>

        {/* 门店 branchNo*/}
        {
          this.renderBranchSelect(branchNo)
        }
        
        {/* 请选择导购 */}
        <Picker
          data={this.state.saleMan}
          cols={1}
          {...getFieldProps('saleman_id', {
            rules: [{ required: true, message: '请选择导购' }],
          })}
        >
          <List.Item arrow="horizontal">选择导购</List.Item>
        </Picker>
      {/* 住址 */}
      <InputItem
          error={!!getFieldError('vip_add')}
          {...getFieldProps('vip_add', {
            rules: [{ required: true, message: '请输入您的住址' }],
          }) }
          placeholder="请输入您的住址"
          style={{height: '1.5rem'}}
        >住址</InputItem>
        {/* 会员卡类型 */}
        {/* {
          isPaidVip && <PaidVip
            shopId={shopId}
            form={this.props.form}
            paidVip={paidVip}
          />
        } */}

    </List>

      <ul  style={{ padding: '.966184rem .531401rem', listStyle: 'none' ,margin: 0}}>
        <li>
          <Button 
            type="primary"  
            style={{border: 'none', height: '1.15942rem',lineHeight: '1.15942rem',fontSize: '.434783rem', background: '#00B3C7', borderRadius: '.144928rem', color: '#fff'}} disabled={this.props.loading} 
            loading={this.props.loading} 
            onClick={() => this.submit()}>
              {this.props.regBtnText}
          </Button>
        </li>
      </ul>
    </div>
    </div>
    );
  }
}

VipRegForm.propTypes = {
  branchNo: React.PropTypes.string,
  salemanId: React.PropTypes.string,
  openid: React.PropTypes.string,
  regBtnText: React.PropTypes.string,
  closable: React.PropTypes.bool,
  loading: React.PropTypes.bool,
  location: React.PropTypes.object,
  branchList: React.PropTypes.array,
  onClose: React.PropTypes.func,
  onSubmit: React.PropTypes.func,
};


VipRegForm.defaultProps = {
  regBtnText: '确定',
  closable: true,
};

export default createForm()(VipRegForm);
